# Copyright (c) 2022 Presto Labs Pte. Ltd.
# Author: daniel

import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo


trade_symbol = ['FX_BTC_JPY', 'BTC_JPY', 'ETH_JPY']


def gen_var_price_ticks(native_symbol):
  price_list = [1e9, 0]
  tick_list = [1]

  range_list = list(zip(price_list[:-1], price_list[1:]))
  result = []
  for r, tick in zip(range_list, tick_list):
    assert r[0] > r[1]
    info = {
        'from': r[1],
        'to': r[0],
        'value': tick,
    }
    result.append([info['from'], info['to'], info['value']])
  return result


def gen_var_qty_ticks(native_symbol):
  qty_ticksize = 1e-9
  if 'FX_BTC_JPY' == native_symbol:
    qty_ticksize = 0.01
  elif 'BTC_JPY' == native_symbol:
    qty_ticksize = 0.00000001
  elif 'ETH_JPY' == native_symbol:
    qty_ticksize = 0.0000001
  return qty_ticksize



def gen_native_base_quote(native_symbol):
  base = None
  quote = None
  if native_symbol == 'FX_BTC_JPY':
    quote, base = 'BTC', 'JPY'
  else:
    quote, base = native_symbol.split('_')
  return base, quote


def gen_norm_symbol(native_symbol):
  norm_symbol = None
  if 'FX_BTC_JPY' == native_symbol:
    norm_symbol = 'BTC-JPY.PERPETUAL'
  elif 'BTC_JPY' == native_symbol:
    norm_symbol = 'BTC-JPY.IMMEDIATE'
  elif 'ETH_JPY' == native_symbol:
    norm_symbol = 'ETH-JPY.IMMEDIATE'
  return norm_symbol


def generate():
  mea = 'Futures.Bitflyer.v1'
  me = 'Futures.Bitflyer'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = requests.get('https://api.bitflyer.com/v1/markets').json()

  pis = []
  for info in data:
    if info['product_code'] not in trade_symbol:
      continue
    native_symbol = info['product_code']
    native_quote, native_base = gen_native_base_quote(native_symbol)
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    symbol = gen_norm_symbol(native_symbol)

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        is_inverse=False,
        price_ticksize=gen_var_price_ticks(native_symbol),
        qty_ticksize=gen_var_qty_ticks(native_symbol),
    )

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


def gen_coin1_constants():
  data = generate()
  data = convert_coin1_constants(data)
  return data


def convert_coin1_constants(data):
  base_currency_list = [info['native_base'] for info in data]
  res = {
      'coin_list': list(set(base_currency_list)),
  }
  return res


if __name__ == '__main__':
  import json
  config = generate()
  print(json.dumps(config, indent=2))
